<template>
    <div class="ct-bodySet">
        <el-container>
            <el-header  class="bgclr-dk-sp0 mb20 headerCoster" style="position: fixed; z-index: 101; left: 200px; top: 60px; right: 0;">
                <el-breadcrumb  separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/mainPage/welcome' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>字段管理</el-breadcrumb-item>
                    <el-breadcrumb-item><span class="main-Clr-ft">研发管理</span></el-breadcrumb-item>
                </el-breadcrumb>
            </el-header>
            <el-container  class="pl20 pr20 mt80 disFlex">
                <el-card  class="mr15 leftMinWidth autoHeight">
                    <div slot="header">
                        <span>研发管理</span>
                    </div>
                    <el-tree :data="productTreeData" :props="productTreeDataProps" ref="productTree" default-expand-all highlight-current
                             :expand-on-click-node="false" node-key="id"@node-click="handleNodeClick">
                            <span slot-scope="{ node, data }">
                                <span class="labelstyleTree tx-Elps" :title="node.label" v-if="data.id!==''" >{{ node.label }}</span>
                                <span class="labelstyleTree tx-Elps main-Clr-ft" v-else :title="node.label">{{ node.label }}</span>
                                <span v-if="onlyAdd(data.id)"><el-button type="text" icon="iconfont icon-tianjia" @click.stop="productAppend(data)"></el-button></span>
                                    <span v-else-if="data.id">
                                        <i class="iconfont icon-tianjia main-Clr-ft ml2 mr2" title="添加" @click.stop="productAppend(data)"></i>
                                        <i class="iconfont icon-shanchu main-Clr-ft" title="删除" v-if="treeRemove(data.children.length)" @click.stop="() =>productRemove(node, data)"></i>
                                    </span>
                                    <span v-else><el-button icon="iconfont icon-shanchu" title="取消添加" type="text" v-if="treeRemove(data.children.length)" @click.stop="() =>productRemove(node, data)"></el-button></span>
                            </span>
                    </el-tree>
                </el-card>
                <el-card v-show="showFlag" class="cardAllWidth autoHeight RightFlex">
                    <div slot="header">
                            <span v-if="flage">
                                新建<span class=" main-Clr-ft ml2 mr2">{{ oldParentName }}</span>的下级产品
                            </span>
                        <span v-else >当前编辑产品<span class="main-Clr-ft"> {{ oldProductName }}</span></span>
                    </div>
                    <el-form  :model="formData" ref="formData" :rules="formRules" label-width="18%">
                        <el-form-item label="产品名称:" prop="productName">
                            <el-input placeholder="请输入产品名称" v-model.trim="formData.productName" size="small" class="formLayoutW"></el-input>
                        </el-form-item>
                        <el-form-item label="产品编号:">
                            <el-col class="formLayoutW" v-if="flage">提交后系统创建</el-col>
                            <el-col class="formLayoutW" v-else>{{formData.id}}</el-col>
                        </el-form-item>

                        <el-form-item label="可用状态:" prop="enable">
                            <el-switch
                                    v-model="formData.enable"
                                    active-text="可用"
                                    inactive-text="不可用">
                            </el-switch>
                        </el-form-item>
                        <el-form-item  label="负责人:"  prop="userId" min-width="13%" height=200>
                             <el-select v-model="formData.userId" filterable>
                                <el-option
                                        v-for="item2 in userAll"
                                        :label="item2.value"
                                        :value="item2.code">
                                </el-option>
                             </el-select>
                        </el-form-item>
                        <el-form-item label="产品顺序:" prop="orderNum">
                            <el-input placeholder="请输入产品顺序" type="number" v-model.trim="formData.orderNum" size="small" class="formLayoutW"></el-input>
                        </el-form-item>
                        <el-form-item label="产品描述:"  prop="summary">
                            <el-input placeholder="请输入产品描述" size="small" type="textarea" :rows="8" v-model.trim="formData.summary" class="formLayoutW"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="small" @click="submitForm('formData')">提交</el-button>
                            <el-button class="bkmgColor" size="small" v-if="flage" @click="resetForm('formData')">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-container>
            <div class="bottomLayoutBus"></div>
        </el-container>
    </div>
</template>

<script>
    import Vue from 'vue';
    import urlConfig from '../../../config/url.json';
    import { Message } from 'element-ui';

    Vue.component(Message.name,Message);
    export default {
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入产品顺序'));
                } else {
                    if(!/^[0-9]+$/.test(value)) {
                        callback(new Error('产品顺序必须为数字'));
                    }
                    callback();
                }
            };
            return {
                flage:false,                            //标记是否添加
                showFlag:false,
                oldId:'',
                oldProductName:'',
                oldOrderNum:'',
                oldSummary:'',
                oldEnable:false,                              //是否可用
                oldUserId:'',
                userAll:[],
                formData: {
                    id:'',
                    productName:'',
                    orderNum:'',
                    userId:'',
                    summary:'',
                    parentId:'',
                    enable: '',
                    children:[]
                },
                formRules:{
                    productName:[
                        { required: true, message: '请输入菜单名称', trigger: 'blur' },
                        {  max: 100, message: '长度在100个字符以内', trigger: 'blur' }
                    ],
                    orderNum:[
                        { required: true,validator: validatePass, trigger: 'blur'},
                        {  max: 3, message: '长度在3个字符以内', trigger: 'blur' }
                    ],
                    summary:[
                        {  max: 255, message: '长度在255个字符以内', trigger: 'blur' }
                    ],
                    enable:[
                        {  required: true, trigger: 'blur' }
                    ]
                },
                productTreeData: [{
                    id:-1,
                    productName:'产品根结点',
                    children:[]
                }],
                productTreeDataProps:{
                    children: 'children',
                    label: 'productName',
                },
                oldParentName:''
            }
        },
        methods:{

            onlyAdd(id){
                return id=='-1';
            },

            treeRemove(length){
                return length==0;
            },

            //选择树节点时触发
            handleNodeClick(data) {
                if(data.id=='-1'){
                    //如果点击的是虚拟根节点 不做任何操作
                    return;
                }
                let that = this;
                if (that.flage) {
                    //添加过程中不允许做其他操作
                    Message.warning('请先完成本次添加');
                } else if(!that.formChange()){
                    //修改过程中  点击其他节点弹出提示
                    this.$confirm('是否取消当前操作', '警告', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        //点击'是'之后
                        that.formData.id = that.oldId;
                        that.formData.productName = that.oldProductName;
                        that.formData.orderNum = that.oldOrderNum;
                        that.formData.summary = that.oldSummary;
                        that.formData.enable = that.oldEnable;
                        that.formData.userId = that.oldUserId;
                        this.$message({
                            type: 'info',
                            message: '操作已取消'
                        });
                    }).catch(() => {
                        //点击'否'之后
                        this.$message({
                            type: 'info',
                            message: '请继续操作'
                        });
                        this.$refs.productTree.setCurrentKey(that.oldId);
                    });
                }
                else{
                    that.getProductInfoByProductId(data.id);//查询菜单信息
                }
            },
            //通过菜单id查询菜单信息
            getProductInfoByProductId(id){
                let that = this;
                that.$refs['formData'].clearValidate();
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                        method: 'get',
                        url: urlConfig.getProductInfoByProductId,
                        baseURL: '/api',
                        params: {
                            id: id
                        }
                    }
                ).then(function (response) {
                    if (response.data.code==200) {
                        if (!response.data.data) {
                            return;
                        }
                        that.showFlag = true;
                        that.formData = response.data.data.dcProduct;
                        //点击节点后 对比用的属性值 需要跟表单值同步
                        that.oldId = response.data.data.dcProduct.id;
                        that.oldProductName = response.data.data.dcProduct.productName;
                        that.oldOrderNum = response.data.data.dcProduct.orderNum;
                        that.oldSummary = response.data.data.dcProduct.summary;
                        that.oldUserId = response.data.data.dcProduct.userId;
                        //判断是否可用
                        if(response.data.data.dcProduct.enable===1){
                            that.oldEnable=true;
                            that.formData.enable=true;
                        }else{
                            that.oldEnable=false;
                            that.formData.enable=false;
                        }
                    }else{
                        Message.error('获取失败')
                    }
                    loading.close();
                }).catch(function (err) {
                    Message.error('获取失败');
                    loading.close();
                });
            },
            //添加节点触发
            productAppend(data){
                let that = this;
                if (that.flage) {
                    //添加过程中  点击其他添加按钮弹出提示
                    Message.warning('请先完成本次添加');
                } else if(!that.formChange()) {
                    //修改过程中  点击其他添加按钮弹出提示
                    this.$confirm('是否放弃本次修改', '警告', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        that.formData.id = that.oldId;
                        that.formData.productName = that.oldProductName;
                        that.formData.orderNum = that.oldOrderNum;
                        that.formData.summary = that.oldSummary;
                        that.formData.enable = that.oldEnable;
                        that.formData.userId = that.oldUserId;
                        this.$message({
                            type: 'info',
                            message: '操作已取消'
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '请继续操作'
                        });
                        this.$refs.productTree.setCurrentKey(that.oldId);
                    })
                }
                else {
                    that.showFlag = true;
                    that.$refs['formData'].clearValidate();
                    const newChild = {
                        id: '',
                        productName: '新菜单',
                        parentId: data.id,
                        orderNum: '',
                        summary: '',
                        userId:'',
                        enable:true,
                        children: []
                    };
                    if (!data.children) {
                        this.$set(data, 'children', []);
                    }
                    data.children.push(newChild);
                    that.formData = newChild;
                    that.oldId = newChild.id;
                    that.oldProductName = newChild.productName;
                    that.oldOrderNum = newChild.orderNum;
                    that.oldSummary = newChild.summary;
                    that.oldEnable = newChild.enable;
                    that.oldUserId = newChild.userId;
                    that.oldParentName = data.productName;
                    that.flage = true;
                }
            },
            productRemove(node, data) {
                let that =this;
                if(!data.id){
                    //添加过程中  点击其他删除按钮弹出提示
                    this.$confirm('是否删除当前新增节点', '警告', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        const parent = node.parent;
                        const children = parent.data.children || parent.data;
                        const index = children.findIndex(d => d.id === data.id);
                        children.splice(index, 1);
                        that.flage=false;
                        this.$message({
                            type: 'info',
                            message: '操作已取消'
                        });
                        that.showFlag = false;
                        that.$refs['formData'].clearValidate();
                        that.formData.id = that.oldId;
                        that.formData.productName = that.oldProductName;
                        that.formData.orderNum = that.oldOrderNum;
                        that.formData.summary = that.oldSummary;
                        that.formData.enable = that.oldEnable;
                        that.formData.userId = that.oldUserId;
                        // that.$refs['formData'].resetFields();
                        this.productRequest('',1);
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '请继续操作'
                        });
                    });
                }
                else if (that.flage) {
                    Message.warning('请先完成本次添加');
                } else if(!that.formChange()) {
                    this.$confirm('是否删除当前新增节点', '警告', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        that.formData.id = that.oldId;
                        that.formData.productName = that.oldProductName;
                        that.formData.orderNum = that.oldOrderNum;
                        that.formData.summary = that.oldSummary;
                        that.formData.enable = that.oldEnable;
                        that.$refs.productTree.setCurrentKey(that.oldId);
                        this.$message({
                            type: 'info',
                            message: '操作已取消'
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '请继续操作'
                        });
                    });
                }else {
                    that.$refs['formData'].clearValidate();
                    this.$confirm('确定要删除    <span class="main-Clr-ft">' + data.productName + '</span>    产品项吗？', '温馨提示', {
                        dangerouslyUseHTMLString: true,
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let that =this;
                        that.$refs['formData'].clearValidate();
                        const loading = this.$loading({
                            lock: true,
                            text: 'Loading',
                            spinner: 'el-icon-loading',
                        });
                        this.$http({
                            method: 'delete',
                            url: urlConfig.productManage,
                            baseURL: '/api',
                            data: {
                                "id": data.id,
                            }
                        }).then(function (response) {
                            if (response.data.code > 199 && response.data.code < 400) {
                                Message.success('删除成功');
                                that.showFlag=false;
                            }else{
                                Message.error('删除失败')
                            }
                            loading.close();
                            that.productRequest('',1)
                        }).catch(function (err) {
                            Message.error('删除失败');
                            loading.close();
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }
            },
            submitForm(formName) {
                debugger;
                let that = this;
                let enableNum;
                //根据true/false值转换为1/0值
                if(that.formData.enable){
                    enableNum=1;
                }else{
                    enableNum=0;
                }
                if(that.flage) {
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            let that = this;
                            const loading = this.$loading({
                                lock: true,
                                text: 'Loading',
                                spinner: 'el-icon-loading',
                            });
                            this.$http({
                                method: 'post',
                                url: urlConfig.productManage,
                                baseURL: '/api',
                                data: {
                                    "productName": that.formData.productName,
                                    "orderNum": that.formData.orderNum,
                                    "parentId": that.formData.parentId,
                                    "summary":that.formData.summary,
                                    "enable":enableNum,
                                    "userId":that.formData.userId,
                                }
                            }).then(function (response) {
                                if (response.data.code > 199 && response.data.code < 400) {
                                    Message.success('添加成功');
                                    that.formData.id = response.data.data.id;
                                    that.oldId = that.formData.id;
                                    that.oldProductName = that.formData.productName;
                                    that.oldOrderNum = that.formData.orderNum;
                                    that.oldSummary = that.formData.summary;
                                    that.oldEnable = that.formData.enable;
                                    that.oldUserId = that.formData.userId;
                                    that.productRequest('',1);
                                }else {
                                    Message.error('添加失败');
                                }
                                that.flage=false;
                                loading.close();
                            }).catch(function (err) {
                                Message.error('添加失败');
                                that.flage=false;
                                that.productRequest('',1);
                                loading.close();
                            });
                        }
                    });
                }
                else{
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            let that = this;
                            const loading = this.$loading({
                                lock: true,
                                text: 'Loading',
                                spinner: 'el-icon-loading',
                            });
                            this.$http({
                                method: 'put',
                                url: urlConfig.productManage,
                                baseURL: '/api',
                                data:{
                                    "id": that.formData.id,
                                    "productName": that.formData.productName,
                                    "orderNum": that.formData.orderNum,
                                    "parentId": that.formData.parentId,
                                    "summary":that.formData.summary,
                                    "enable":enableNum,
                                    "userId":that.formData.userId,
                                }
                            }).then(function(response){
                                if(response.data.code>199 && response.data.code<400) {
                                    if (!response.data.data) {
                                        return;
                                    }
                                    Message.success('修改成功');
                                    that.oldId = that.formData.id;
                                    that.oldProductName = that.formData.productName;
                                    that.oldOrderNum = that.formData.orderNum;
                                    that.oldSummary = that.formData.summary;
                                    that.oldEnable = that.formData.enable;
                                    that.oldUserId = that.formData.userId;
                                    that.productRequest('',1);
                                }else{
                                    Message.error('修改失败');
                                }
                                loading.close();
                            }).catch(function(err){
                                Message.error('修改失败');
                                loading.close();
                            });
                        }
                    });
                }
            },
            getJsonTree(newdata,parentId){
                let that = this;
                let itemArr=[];
                for(let i=0;i<newdata.length;i++){
                    let node=newdata[i];
                    if(node.parentId==parentId ){
                        let newNode={
                            id:node.id,
                            productName:node.productName,
                            orderNum:node.orderNum,
                            parentId:node.parentId,
                            summary:node.summary,
                            enable:node.enable,
                            userId:node.userId,
                            children:that.getJsonTree(newdata,node.id)
                        };
                        itemArr.push(newNode);
                    }
                }
                itemArr.sort(that.up);
                return itemArr;
            },
            //发送产品树查询请求
            productRequest(id,editImg) {
                let that=this;
                const loading = that.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                        method:'get',
                        url:urlConfig.productManage,
                        baseURL:'/api',
                        params:{
                            id:id
                        }
                    }
                ).then(function (response) {
                    if(response.data.code>199 && response.data.code<400) {
                        let newdata=response.data.data.dcProductList;
                        that.productTreeData[0].children =that.getJsonTree(newdata, '-1');
                        for (let i = 0; i < that.productTreeData[0].children.length; i++) {
                            that.productTreeData[0].children[i].parentId = '0'
                        }
                        debugger;
                    }else {
                        Message.error('获取失败')
                    }
                    loading.close();
                }).catch(function (err) {
                    Message.error('获取失败');
                    loading.close();
                });
            },
            up(x,y){
                return x.orderNum-y.orderNum
            },
            //重置表单
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            

            formChange(){
                let that =this;
                if(that.oldUserId!=that.formData.userId||that.oldProductName!=that.formData.productName||that.oldOrderNum!=that.formData.orderNum||that.oldSummary!=that.formData.summary||that.oldEnable!=that.formData.enable){
                    return false
                }else return true
            }
        },
        mounted() {
            let that = this;
            that.productRequest('',1);
            that.userAll = JSON.parse(that.STORAGE.getItem("userAll"));

        }
    }
</script>
.formLayoutW
<style scoped>
    .headerCoster{
        height: 59px;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
    }

    .formLayoutW{
        width: 77%;
    }

    .leftMinWidth {
        min-width: 275px;
    }

    .cardAllWidth {
        width: 100%;
    }

    .autoHeight {
        min-height:calc(100vh - 180px);
    }

    .mt80 {
        margin-top: 80px;
    }

    .disFlex {
        display: flex;
    }

    .RightFlex {
        flex: 1;
    }
</style>